package com.umeox.watch.arithmetictest.io;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by jarly on 2018/11/23.
 * <p>
 * 线程管理
 */

public class ThreadExecutor {

    private Executor mainExecutor;

    private ThreadPoolExecutor mIoExecutor;

    public ThreadExecutor(Executor mainExecutor) {
        this.mainExecutor = mainExecutor;

        ThreadFactory nameThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("pool-%d")
                .build();
        mIoExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024), nameThreadFactory,
                new ThreadPoolExecutor.AbortPolicy());
    }

    private ThreadExecutor() {
        this(new MainThreadExecutor());
    }

    public Executor main() {
        return mainExecutor;
    }

    public ThreadPoolExecutor io() {
        return mIoExecutor;
    }


    public static ThreadExecutor getInstance() {
        return InstanceHolder.mThreadExecutor;
    }

    private static class InstanceHolder {
        private static final ThreadExecutor mThreadExecutor = new ThreadExecutor();
    }
}
